# -*- coding: utf-8 -*-

import smtplib
import threading
from email.mime.text import MIMEText
from tornado import gen
from tornado.queues import Queue
from apps import configs
# from apps.log import logging
import logging
class EmailException(Exception):
    pass


class Email(object):
    @staticmethod
    def send_mail(addressee, name, body):
        message = MIMEText(body, 'html', 'utf-8')
        message['From'] = configs.MAIL['from']
        message['To'] = ','.join(addressee)
        message['Subject'] = name

        try:
            smtp = smtplib.SMTP_SSL(configs.MAIL['host'], configs.MAIL['port'])
            smtp.login(configs.MAIL['name'], configs.MAIL['password'])
            smtp.sendmail(configs.MAIL['name'], addressee, message.as_string())
            smtp.quit()
            logging.info(str(addressee) + '发送成功')
        except smtplib.SMTPRecipientsRefused as e:
            raise EmailException(e)
        except smtplib.SMTPAuthenticationError as e:
            raise EmailException(e)
        except smtplib.SMTPSenderRefused as e:
            raise EmailException(e)
        except smtplib.SMTPException as e:
            raise EmailException(e)


class EmailQueue(object):
    _queque = Queue()

    def __init__(self):
        pass

    @staticmethod
    async def start():
        while True:
            msg = await EmailQueue._queque.get()
            logging.info(str(msg))
            try:
                threading.Thread(target=Email.send_mail,
                                 args=(msg['addressee'], msg['name'],
                                       msg['body'])).start()
                await gen.sleep(0.01)
            finally:
                EmailQueue._queque.task_done()

    @staticmethod
    async def send(addressee, name, body):
        msg = dict()
        msg['addressee'] = addressee
        msg['name'] = name
        msg['body'] = body
        await EmailQueue._queque.put(msg)
